package com.atguigu_f_countdownlatch;

import java.util.concurrent.CountDownLatch;

public class Demo {
    public static void main(String[] args) {
        //创建 CountDownLatch对象
        CountDownLatch count = new CountDownLatch(3);

        //创建线程对象
        Mother mother = new Mother("李夫人",count);
        Child1 child1 = new Child1("金吒",count);
        Child2 child2 = new Child2("木吒",count);
        Child3 child3 = new Child3("哪吒",count);

        //启动线程
        mother.start();
        child1.start();
        child2.start();
        child3.start();
    }
}


//四个线程 : 3个孩子线程 1个妈妈线程
class Mother extends Thread{
    private CountDownLatch count;

    public Mother(String name, CountDownLatch count) {
        super(name);
        this.count = count;
    }

    @Override
    public void run() {
        //妈妈先等
        try {
            count.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //能走下来说明孩子们[其他线程]已经执行完毕
        System.out.println("姓名是 : " + getName() + " 的妈妈开始洗碗 !!");
    }
}

class Child1 extends Thread{
    private CountDownLatch count;

    public Child1(String name, CountDownLatch count) {
        super(name);
        this.count = count;
    }
    @Override
    public void run() {
        //吃饭
        for (int i = 1; i <= 20; i++) {
            System.out.println("姓名是 : " + getName() + " 的孩子吃了第 " + i + " 个饺子 ! ");
        }

        //知会妈妈吃完了 --> 计数器减一
        count.countDown();
    }
}

class Child2 extends Thread{
    private CountDownLatch count;

    public Child2(String name, CountDownLatch count) {
        super(name);
        this.count = count;
    }
    @Override
    public void run() {
        //吃饭
        for (int i = 1; i <= 10; i++) {
            System.out.println("姓名是 : " + getName() + " 的孩子吃了第 " + i + " 个饺子 ! ");
        }

        //知会妈妈吃完了 --> 计数器减一
        count.countDown();
    }
}

class Child3 extends Thread{
    private CountDownLatch count;

    public Child3(String name, CountDownLatch count) {
        super(name);
        this.count = count;
    }
    @Override
    public void run() {
        //吃饭
        for (int i = 1; i <= 15; i++) {
            System.out.println("姓名是 : " + getName() + " 的孩子吃了第 " + i + " 个饺子 ! ");
        }

        //知会妈妈吃完了 --> 计数器减一
        count.countDown();
    }
}